package com.winsomely.leecode;

/**
 * 合并两个有序数组
 * 
 * @author liujiawei
 *
 */
public class Merge {

	public void merge(int[] nums1, int m, int[] nums2, int n) {
		if (n == 0) {
			return;
		}
		if (m == 0) {
			System.arraycopy(nums2, 0, nums1, 0, nums2.length);
			return;
		}
		int i = 0, mi = 0, ni = 0, max = m + n;
		int[] result = new int[m + n];
		while (i < max) {
			if (mi >= m && ni < n) {
				result[i++] = nums2[ni++];
			} else if (ni >= n && mi < m) {
				result[i++] = nums1[mi++];
			} else if (nums1[mi] <= nums2[ni]) {
				result[i++] = nums1[mi++];
			} else if (nums1[mi] >= nums2[ni]) {
				result[i++] = nums2[ni++];
			}
		}
		System.arraycopy(result, 0, nums1, 0, result.length);
	}

	public static void main(String[] args) {
		Merge t = new Merge();

		int[] nums1 = { -9, -6, 0, 5, 8, 0, 0, 0, 0, 0, 0 };
		int[] nums2 = { -11, -2, 0, 5, 10, 13 };
		int m = 5;
		int n = 6;
		t.merge(nums1, m, nums2, n);
		for (int s : nums1) {
			System.out.print(s + ", ");
		}

	}

}
